package cn.harry.cabinet.viewmodel

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import cn.harry.cabinet.database.AppDatabase
import cn.harry.cabinet.model.entity.Configuration
import cn.harry.cabinet.receiver.AutoRestartReceiver
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.utils.AppConfigKeys
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 程序管理ViewModel
 * 负责应用管理、系统监控、定时重启和数据库备份功能
 */
class ProgramManagementViewModel(application: Application) : BaseViewModel(application) {
    
    private val context: Context = application.applicationContext
    private val database = AppDatabase.getDatabase(context)
    private val configRepository = ConfigurationRepository(application)
    
    // 系统监控相关
    private val _monitorStatus = MutableLiveData<String>()
    val monitorStatus: LiveData<String> = _monitorStatus
    
    private val _memoryInfo = MutableLiveData<String>()
    val memoryInfo: LiveData<String> = _memoryInfo
    
    private val _cpuInfo = MutableLiveData<String>()
    val cpuInfo: LiveData<String> = _cpuInfo
    
    private val _processInfo = MutableLiveData<String>()
    val processInfo: LiveData<String> = _processInfo
    
    private val _isMonitoring = MutableLiveData<Boolean>()
    val isMonitoring: LiveData<Boolean> = _isMonitoring
    
    // 定时重启相关
    private val _scheduledRestartEnabled = MutableLiveData<Boolean>()
    val scheduledRestartEnabled: LiveData<Boolean> = _scheduledRestartEnabled
    
    private val _restartTime = MutableLiveData<String>()
    val restartTime: LiveData<String> = _restartTime
    
    // 数据库备份相关
    private val _backupStatus = MutableLiveData<String>()
    val backupStatus: LiveData<String> = _backupStatus
    
    private var monitoringJob: Job? = null
    
    init {
        _monitorStatus.value = "监控已停止"
        _isMonitoring.value = false
        _memoryInfo.value = "等待监控数据..."
        _cpuInfo.value = "等待监控数据..."
        _processInfo.value = "等待监控数据..."
        _backupStatus.value = "未进行备份操作"
        
        // 不设置默认值，等待从数据库加载
        // _scheduledRestartEnabled 和 _restartTime 将在 loadScheduledRestartSettings() 中设置
        loadScheduledRestartSettings()
    }
    
    /**
     * 启动系统监控
     */
    fun startMonitoring() {
        if (_isMonitoring.value == true) {
            return
        }
        
        _isMonitoring.value = true
        _monitorStatus.value = "监控运行中..."
        
        monitoringJob = viewModelScope.launch {
            while (isActive) {
                updateSystemInfo()
                delay(2000) // 每2秒更新一次
            }
        }
    }
    
    /**
     * 停止系统监控
     */
    fun stopMonitoring() {
        monitoringJob?.cancel()
        monitoringJob = null
        _isMonitoring.value = false
        _monitorStatus.value = "监控已停止"
    }
    
    /**
     * 更新系统信息
     */
    private suspend fun updateSystemInfo() {
        withContext(Dispatchers.IO) {
            try {
                // 获取内存信息
                val memInfo = getMemoryInfo()
                _memoryInfo.postValue(memInfo)
                
                // 获取CPU信息
                val cpuInfo = getCpuInfo()
                _cpuInfo.postValue(cpuInfo)
                
                // 获取进程信息
                val procInfo = getProcessInfo()
                _processInfo.postValue(procInfo)
                
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 获取内存信息
     */
    private fun getMemoryInfo(): String {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        
        val totalMemory = memoryInfo.totalMem / (1024 * 1024) // MB
        val availableMemory = memoryInfo.availMem / (1024 * 1024) // MB
        val usedMemory = totalMemory - availableMemory
        val usagePercent = (usedMemory.toFloat() / totalMemory * 100).toInt()
        
        // 获取应用内存使用
        val runtime = Runtime.getRuntime()
        val appMaxMemory = runtime.maxMemory() / (1024 * 1024)
        val appUsedMemory = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024)
        
        return """
            系统内存:
            • 总内存: ${totalMemory}MB
            • 已用: ${usedMemory}MB (${usagePercent}%)
            • 可用: ${availableMemory}MB
            
            应用内存:
            • 最大可用: ${appMaxMemory}MB
            • 已使用: ${appUsedMemory}MB
        """.trimIndent()
    }
    
    /**
     * 获取CPU信息
     */
    private fun getCpuInfo(): String {
        return try {
            val cpuCount = Runtime.getRuntime().availableProcessors()
            
            // 读取CPU使用率（简化版本）
            val stat1 = readCpuStat()
            Thread.sleep(100)
            val stat2 = readCpuStat()
            
            val usage = calculateCpuUsage(stat1, stat2)
            
            """
                CPU信息:
                • 核心数: $cpuCount
                • 使用率: ${String.format("%.1f", usage)}%
            """.trimIndent()
        } catch (e: Exception) {
            "CPU信息获取失败: ${e.message}"
        }
    }
    
    /**
     * 读取CPU统计信息
     */
    private fun readCpuStat(): LongArray {
        try {
            val reader = File("/proc/stat").bufferedReader()
            val line = reader.readLine()
            reader.close()
            
            val tokens = line.split("\\s+".toRegex())
            return longArrayOf(
                tokens[1].toLong(),
                tokens[2].toLong(),
                tokens[3].toLong(),
                tokens[4].toLong()
            )
        } catch (e: Exception) {
            return longArrayOf(0, 0, 0, 0)
        }
    }
    
    /**
     * 计算CPU使用率
     */
    private fun calculateCpuUsage(stat1: LongArray, stat2: LongArray): Double {
        val idle1 = stat1[3]
        val idle2 = stat2[3]
        val total1 = stat1.sum()
        val total2 = stat2.sum()
        
        val totalDiff = total2 - total1
        val idleDiff = idle2 - idle1
        
        return if (totalDiff > 0) {
            ((totalDiff - idleDiff).toDouble() / totalDiff) * 100
        } else {
            0.0
        }
    }
    
    /**
     * 获取进程信息
     */
    private fun getProcessInfo(): String {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val processInfo = activityManager.runningAppProcesses
        
        val currentProcess = processInfo?.find { it.pid == android.os.Process.myPid() }
        
        return if (currentProcess != null) {
            """
                进程信息:
                • 进程名: ${currentProcess.processName}
                • 进程ID: ${currentProcess.pid}
                • 重要性: ${getImportanceString(currentProcess.importance)}
            """.trimIndent()
        } else {
            "进程信息获取失败"
        }
    }
    
    /**
     * 获取进程重要性描述
     */
    private fun getImportanceString(importance: Int): String {
        return when (importance) {
            ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND -> "前台"
            ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE -> "可见"
            ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE -> "服务"
            ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED -> "缓存"
            else -> "未知"
        }
    }
    
    /**
     * 加载定时重启设置
     * 如果数据库中不存在配置，则使用默认值并保存到数据库
     */
    private fun loadScheduledRestartSettings() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                // 默认配置
                val defaultEnabled = false
                val defaultHour = 1
                val defaultMinute = 0
                
                // 获取启用状态
                var enabledConfig = configRepository.getByTypeAndKey(AppConfigKeys.TYPE_SYSTEM, AppConfigKeys.KEY_AUTO_RESTART_ENABLED)
                if (enabledConfig == null) {
                    // 不存在则创建默认配置
                    enabledConfig = Configuration(
                        type = AppConfigKeys.TYPE_SYSTEM,
                        key = AppConfigKeys.KEY_AUTO_RESTART_ENABLED,
                        value = defaultEnabled.toString()
                    )
                    configRepository.create(enabledConfig)
                }
                val enabled = enabledConfig.value?.toBoolean() ?: defaultEnabled
                
                // 获取小时
                var hourConfig = configRepository.getByTypeAndKey(AppConfigKeys.TYPE_SYSTEM, AppConfigKeys.KEY_AUTO_RESTART_HOUR)
                if (hourConfig == null) {
                    // 不存在则创建默认配置
                    hourConfig = Configuration(
                        type = AppConfigKeys.TYPE_SYSTEM,
                        key = AppConfigKeys.KEY_AUTO_RESTART_HOUR,
                        value = defaultHour.toString()
                    )
                    configRepository.create(hourConfig)
                }
                var hour = hourConfig.value?.toIntOrNull() ?: defaultHour
                
                // 获取分钟
                var minuteConfig = configRepository.getByTypeAndKey(AppConfigKeys.TYPE_SYSTEM, AppConfigKeys.KEY_AUTO_RESTART_MINUTE)
                if (minuteConfig == null) {
                    // 不存在则创建默认配置
                    minuteConfig = Configuration(
                        type = AppConfigKeys.TYPE_SYSTEM,
                        key = AppConfigKeys.KEY_AUTO_RESTART_MINUTE,
                        value = defaultMinute.toString()
                    )
                    configRepository.create(minuteConfig)
                }
                val minute = minuteConfig.value?.toIntOrNull() ?: defaultMinute
                
                val time = String.format("%02d:%02d", hour, minute)
                
                _scheduledRestartEnabled.postValue(enabled)
                _restartTime.postValue(time)
                
                // 如果启用了定时重启，确保定时任务已设置
                // 这样在应用重启后也能恢复定时任务
                if (enabled) {
                    AutoRestartReceiver.scheduleDaily(context, hour, minute)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 保存定时重启设置
     */
    fun saveScheduledRestartSettings(enabled: Boolean, time: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val timeParts = time.split(":")
                val hour = timeParts.getOrNull(0)?.toIntOrNull() ?: 1
                val minute = timeParts.getOrNull(1)?.toIntOrNull() ?: 0
                
                // 保存启用状态（upsert：存在则更新，不存在则创建）
                val existingEnabled = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_SYSTEM,
                    AppConfigKeys.KEY_AUTO_RESTART_ENABLED
                )
                if (existingEnabled == null) {
                    configRepository.create(
                        Configuration(
                            type = AppConfigKeys.TYPE_SYSTEM,
                            key = AppConfigKeys.KEY_AUTO_RESTART_ENABLED,
                            value = enabled.toString()
                        )
                    )
                } else {
                    configRepository.update(
                        existingEnabled.copy(
                            value = enabled.toString(),
                            updateTime = java.util.Date()
                        )
                    )
                }
                
                // 保存小时（upsert）
                val existingHour = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_SYSTEM,
                    AppConfigKeys.KEY_AUTO_RESTART_HOUR
                )
                if (existingHour == null) {
                    configRepository.create(
                        Configuration(
                            type = AppConfigKeys.TYPE_SYSTEM,
                            key = AppConfigKeys.KEY_AUTO_RESTART_HOUR,
                            value = hour.toString()
                        )
                    )
                } else {
                    configRepository.update(
                        existingHour.copy(
                            value = hour.toString(),
                            updateTime = java.util.Date()
                        )
                    )
                }
                
                // 保存分钟（upsert）
                val existingMinute = configRepository.getByTypeAndKey(
                    AppConfigKeys.TYPE_SYSTEM,
                    AppConfigKeys.KEY_AUTO_RESTART_MINUTE
                )
                if (existingMinute == null) {
                    configRepository.create(
                        Configuration(
                            type = AppConfigKeys.TYPE_SYSTEM,
                            key = AppConfigKeys.KEY_AUTO_RESTART_MINUTE,
                            value = minute.toString()
                        )
                    )
                } else {
                    configRepository.update(
                        existingMinute.copy(
                            value = minute.toString(),
                            updateTime = java.util.Date()
                        )
                    )
                }
                
                // 更新LiveData
                _scheduledRestartEnabled.postValue(enabled)
                _restartTime.postValue(time)
                
                // 根据开关状态设置或取消定时任务
                if (enabled) {
                    AutoRestartReceiver.scheduleDaily(context, hour, minute)
                } else {
                    AutoRestartReceiver.cancel(context)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                showError("保存设置失败: ${e.message}")
            }
        }
    }
    
    
    /**
     * 备份数据库
     */
    fun backupDatabase(callback: (Boolean, String) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                _backupStatus.postValue("正在备份数据库...")
                
                // 使用 checkpoint 确保所有数据写入磁盘
                database.openHelper.writableDatabase.query("PRAGMA wal_checkpoint(FULL)").close()
                
                // 获取数据库文件
                val dbFile = context.getDatabasePath("app_database")
                if (!dbFile.exists()) {
                    _backupStatus.postValue("数据库文件不存在")
                    callback(false, "数据库文件不存在")
                    return@launch
                }
                
                // 创建备份目录
                val backupDir = File(context.getExternalFilesDir(null), "backup")
                if (!backupDir.exists()) {
                    backupDir.mkdirs()
                }
                
                // 生成备份文件名（带时间戳）
                val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
                val backupFile = File(backupDir, "app_database_backup_$timestamp.db")
                
                // 复制数据库文件
                FileInputStream(dbFile).use { input ->
                    FileOutputStream(backupFile).use { output ->
                        input.copyTo(output)
                    }
                }
                
                val message = "备份成功！\n路径: ${backupFile.absolutePath}"
                _backupStatus.postValue(message)
                callback(true, message)
                
            } catch (e: Exception) {
                e.printStackTrace()
                val message = "备份失败: ${e.message}"
                _backupStatus.postValue(message)
                callback(false, message)
            }
        }
    }
    
    /**
     * 恢复数据库
     */
    fun restoreDatabase(backupFilePath: String, callback: (Boolean, String) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                _backupStatus.postValue("正在恢复数据库...")
                
                val backupFile = File(backupFilePath)
                if (!backupFile.exists()) {
                    val message = "备份文件不存在"
                    _backupStatus.postValue(message)
                    callback(false, message)
                    return@launch
                }
                
                // 获取数据库文件
                val dbFile = context.getDatabasePath("app_database")
                
                // 复制备份文件到数据库位置
                FileInputStream(backupFile).use { input ->
                    FileOutputStream(dbFile).use { output ->
                        input.copyTo(output)
                    }
                }
                
                val message = "恢复成功！应用将重启以应用更改"
                _backupStatus.postValue(message)
                callback(true, message)
                
            } catch (e: Exception) {
                e.printStackTrace()
                val message = "恢复失败: ${e.message}"
                _backupStatus.postValue(message)
                callback(false, message)
            }
        }
    }
    
    /**
     * 列出所有备份文件
     */
    fun listBackupFiles(): List<File> {
        val backupDir = File(context.getExternalFilesDir(null), "backup")
        if (!backupDir.exists()) {
            return emptyList()
        }
        
        return backupDir.listFiles { file ->
            file.name.startsWith("app_database_backup_") && file.name.endsWith(".db")
        }?.sortedByDescending { it.lastModified() } ?: emptyList()
    }
    
    override fun onCleared() {
        super.onCleared()
        stopMonitoring()
    }
}
